package com.java.socket;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;

public class Tools {
	private HashSet<User> allUsers;
	private HashSet<Group> allGroups;
	
	private File user_file;
	private File group_file;
	private File user_info;
	
	public Tools(File user_file,File group_file,File user_info){
		this.user_file=user_file;
		this.group_file=group_file;
		this.user_info=user_info;
		this.allUsers=new HashSet<User>();
		this.allGroups=new HashSet<Group>();
	}
	public void readUserFile(){
		FileInputStream fis=null;
		BufferedReader br=null;
		try {
			fis=new FileInputStream(user_file);
			br=new BufferedReader(new InputStreamReader(fis));
			String str=null;
			if((str=br.readLine())!=null){
				String[] ss=str.split(":");
				User u=new User(Integer.parseInt(ss[2]),ss[0],Integer.parseInt(ss[3]));
				this.allUsers.add(u);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(br!=null) try{br.close();} catch(IOException e) {}
			if(fis!=null) try{fis.close();} catch(IOException e) {}
		}
	}
	public void readGroupFile(){
		FileInputStream fis=null;
		BufferedReader br=null;
		try {
			fis=new FileInputStream(group_file);
			br=new BufferedReader(new InputStreamReader(fis));
			String str=null;
			if((str=br.readLine())!=null){
				String[] ss=str.split(":");
				Group g=new Group(Integer.parseInt(ss[2]),ss[0]);
				this.allGroups.add(g);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(br!=null) try{br.close();} catch(IOException e) {}
			if(fis!=null) try{fis.close();} catch(IOException e) {}
		}
	}
	public void writeUserInfo(){
		FileOutputStream fos=null;
		PrintWriter pw=null;
		try {
			fos=new FileOutputStream(user_info);
			pw=new PrintWriter(fos);
			for(User u:this.allUsers){
				for(Group g:this.allGroups){
					if(u.getGid()==g.getGId()){
						pw.println(u.getUName()+":"+g.getGName());
					}
				}
			}
			pw.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally{
			if(pw!=null) pw.close();
			if(fos!=null)try{fos.close();}catch(IOException e){}
		}
	}
	public static void main(String[] args){
		Tools t=new Tools(new File("/etc/passwd"),new File("/etc/group"),new File("./userinfo.txt"));
		t.readUserFile();
		t.readGroupFile();
		t.writeUserInfo();
		
	}

}
